﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XjjXmm.FrameWork.ToolKit;

namespace XjjXmm.Spider.biquge
{
    internal interface ISetUpProfile
    {
        IServiceCollection Regist(IServiceCollection services);
    }

    internal abstract class AbstractSetUpProfile<T> : ISetUpProfile where T : class, ISiteSpider
    {
        private SiteSetting? _siteSetting;
        //private SiteSetting? SiteSetting
        //{
        //    get
        //    {
        //        if(_siteSetting == null)
        //        {
        //            _siteSetting = Setting.FindSetting<T>();
        //        }

        //        return _siteSetting;
        //    }
        //}
        protected string domain;// => SiteSetting?.Domain??"";
        protected List<string> keys { get; set; } = new List<string> { };

        public AbstractSetUpProfile()
        {
          
            _siteSetting = Setting.FindSetting<T>();

            domain = _siteSetting?.Domain??"";

            keys = Setting.GetKeys<T>();
        }

        protected IHttpClientBuilder AddLogBuild(IHttpClientBuilder build)
        {
            return build.AddHttpMessageHandler<HttpLogHandel<T>>();
        }

        protected abstract void ConfigClient(string key, IServiceCollection services, string? proxy = null);

        public virtual IServiceCollection Regist(IServiceCollection services)
        {
            services.AddSingleton<ISiteSpider, T>();
            services.AddScoped<HttpLogHandel<T>>();
            services.AddSingleton<ClientBuildHelper<T>>();

            var i = 0;
            

            if (_siteSetting?.UseLocal == true)
            {
                ConfigClient(keys[i], services);
                i++;
            }

            

            _siteSetting?.Proxylist?.ForEach(proxy =>
            {
                ConfigClient(keys[i], services, proxy);

                i++;
            });

            return services;

        }
    }
}
